﻿<template>
  <div class="banji-container">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
      <el-form :model="queryParams" ref="queryForm" labelWidth="90">
        <el-row>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item label="关键字">
              <el-input v-model="queryParams.searchKey" clearable="" placeholder="请输入模糊查询关键字"/>
              
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="编号">
              <el-input v-model="queryParams.bianHao" clearable="" placeholder="请输入编号"/>
              
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="班级名称">
              <el-input v-model="queryParams.name" clearable="" placeholder="请输入班级名称"/>
              
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="班主任">
              <el-select clearable="" filterable="" v-model="queryParams.bzrId" placeholder="请选择班主任">
                <el-option v-for="(item,index) in  teacherBzrIdDropdownList" :key="index" :value="item.value" :label="item.label" />
                
              </el-select>
              
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="学段">
              <el-select clearable="" v-model="queryParams.xueduan" placeholder="请选择学段">
                <el-option v-for="(item,index) in dl('bnaji_xueduan')" :key="index" :value="item.code" :label="`[${item.code}] ${item.value}`" />
                
              </el-select>
              
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="级">
              <el-input-number v-model="queryParams.ji"  clearable="" placeholder="请输入级"/>
              
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="班号">
              <el-input-number v-model="queryParams.bh"  clearable="" placeholder="请输入班号"/>
              
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="备注">
              <el-input v-model="queryParams.beizhu" clearable="" placeholder="请输入备注"/>
              
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" class="mb10">
            <el-form-item>
              <el-button-group>
                <el-button type="primary"  icon="ele-Search" @click="handleQuery" v-auth="'banji:page'"> 查询 </el-button>
                <el-button icon="ele-Refresh" @click="() => queryParams = {}"> 重置 </el-button>
                <el-button icon="ele-ZoomIn" @click="changeAdvanceQueryUI" v-if="!showAdvanceQueryUI"> 高级 </el-button>
                <el-button icon="ele-ZoomOut" @click="changeAdvanceQueryUI" v-if="showAdvanceQueryUI"> 隐藏 </el-button>
                
              </el-button-group>
              
              <el-button-group style="margin-left:20px">
                <el-button type="primary" icon="ele-Plus" @click="openAddBanji" v-auth="'banji:add'"> 新增 </el-button>
                <el-button type="primary" icon="ele-Plus" @click="openUploadDialog" v-auth="'teacher:import'"> 导入 </el-button>
                <el-button type="primary" icon="ele-Printer" @click="openPrintBanji" v-auth="'student:print'"> 打印 </el-button>
              </el-button-group>
              
            </el-form-item>
            
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="full-table" shadow="hover" style="margin-top: 8px">
      <el-table
				:data="tableData"
				style="width: 100%"
				v-loading="loading"
				tooltip-effect="light"
				row-key="id"
        @selection-change="handleSelectionChange"
				border="">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="55" align="center"/>
        <el-table-column prop="bianHao" label="编号" width="140" show-overflow-tooltip="" />
        <el-table-column prop="name" label="班级名称" width="140" show-overflow-tooltip="" />
        <el-table-column prop="bzrId" label="班主任" width="120" show-overflow-tooltip="">
          <template #default="scope">
            <span>{{scope.row.bzrIdName}}</span>
            
          </template>
          
        </el-table-column>
          <el-table-column prop="xueduan" label="学段" width="140" show-overflow-tooltip="" >
            <template #default="scope">
              <el-tag :type="di('bnaji_xueduan', scope.row.xueduan)?.tagType"> {{di("bnaji_xueduan", scope.row.xueduan)?.value}} </el-tag>
            </template>
          </el-table-column>
        <el-table-column prop="ji" label="级" width="140" show-overflow-tooltip="" />
        <el-table-column prop="bh" label="班号" width="140" show-overflow-tooltip="" />
        <el-table-column prop="beizhu" label="备注" width="140" show-overflow-tooltip="" />
        <el-table-column prop="isGraduated" label="是否毕业" width="120" show-overflow-tooltip="">
          <template #default="scope">
            <el-tag v-if="scope.row.isGraduated"> 是 </el-tag>
            <el-tag type="danger" v-else> 否 </el-tag>
            
          </template>
          
        </el-table-column>
        <el-table-column label="操作" width="140" align="center" fixed="right" show-overflow-tooltip="" v-if="auth('banji:edit') || auth('banji:delete')">
          <template #default="scope">
            <el-button icon="ele-Edit" size="small" text="" type="primary" @click="openEditBanji(scope.row)" v-auth="'banji:edit'"> 编辑 </el-button>
            <el-button icon="ele-Delete" size="small" text="" type="primary" @click="delBanji(scope.row)" v-auth="'banji:delete'"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
				v-model:currentPage="tableParams.page"
				v-model:page-size="tableParams.pageSize"
				:total="tableParams.total"
				:page-sizes="[10, 20, 50, 100, 200, 500]"
				small=""
				background=""
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper"
	/>
      <printDialog
        ref="printDialogRef"
        :title="printBanjiTitle"
        @reloadTable="handleQuery" />
      <editDialog
        ref="editDialogRef"
        :title="editBanjiTitle"
        @reloadTable="handleQuery"
      />
    </el-card>
    
    <el-dialog v-model="state.dialogUploadVisible" :lock-scroll="false" draggable width="400px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-UploadFilled /> </el-icon>
					<span> 上传文件 </span>
				</div>
			</template>
			<div>
				<el-upload ref="uploadRef" drag :auto-upload="false" :limit="1" :file-list="state.fileList" action="" :on-change="handleChange" accept=".jpg,.png,.bmp,.gif,.txt,.pdf,.xlsx,.docx">
					<el-icon class="el-icon--upload">
						<ele-UploadFilled />
					</el-icon>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					<template #tip>
						<div class="el-upload__tip">请上传大小不超过 10MB 的文件</div>
            <el-link @click="download">导入模板下载</el-link>
					</template>
				</el-upload>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.dialogUploadVisible = false">取消</el-button>
					<el-button type="primary" @click="uploadFile">确定</el-button>
				</span>
			</template>
		</el-dialog>
    <el-dialog v-model="state.dialogImportVisible" :lock-scroll="false" draggable width="1000px">
			<div>
        <el-table
          :data="importData"
          style="width: 100%"
          v-loading="loading"
          tooltip-effect="light"
          border="">
          <el-table-column prop="bianHao" label="编号" width="140" show-overflow-tooltip="" />
          <el-table-column prop="name" label="班级名称" width="140" show-overflow-tooltip="" />
          <el-table-column prop="xueduan" label="学段" width="140" show-overflow-tooltip="" />
          <el-table-column prop="ji" label="级" width="140" show-overflow-tooltip="" />
          <el-table-column prop="bh" label="班号" width="140" show-overflow-tooltip="" />
          <el-table-column prop="bzrName" label="班主任" width="140" show-overflow-tooltip="" />
          <el-table-column prop="isGraduated" label="是否毕业" width="140" show-overflow-tooltip="" />
          <el-table-column prop="msg" label="导入检查消息" width="140" show-overflow-tooltip="" />
        </el-table>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.dialogImportVisible = false">取消</el-button>
					<el-button type="primary" @click="Import">确定</el-button>
				</span>
			</template>
		</el-dialog>
  </div>
</template>

<script lang="ts" setup="" name="banji">
  import { ref,reactive} from "vue";
  import { ElMessageBox, ElMessage,UploadInstance } from "element-plus";
  import { auth } from '/@/utils/authFunction';
  import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
  import { formatDate } from '/@/utils/formatTime';


  import printDialog from '/@/views/system/print/component/hiprint/preview.vue'
  import editDialog from '/@/views/main/banji/component/editDialog.vue'
  import { pageBanji, deleteBanji,importPreviewBanji,importBanji } from '/@/api/main/banji';
  import { pageStudent } from '/@/api/main/student';
  import { getTeacherBzrIdDropdown } from '/@/api/main/banji';

  import { SysFileApi } from '/@/api-services/api';
  import { SysFile } from '/@/api-services/models';

  import { downloadByUrl } from '/@/utils/download';

  import { getAPI } from '/@/utils/axios-utils';

  import { hiprint } from 'vue-plugin-hiprint';
  import { SysPrintApi } from '/@/api-services/api';
  import { SysPrint } from '/@/api-services/models';

  const uploadRef = ref<UploadInstance>();
  const state = reactive({
    loading: false,
    fileData: [] as Array<SysFile>,
    queryParams: {
      fileName: undefined,
      startTime: undefined,
      endTime: undefined,
    },
    tableParams: {
      page: 1,
      pageSize: 10,
      total: 0 as any,
    },
    dialogUploadVisible: false,
    diaglogEditFile: false,
    fileList: [] as any,
    dialogDocxVisible: false,
    dialogXlsxVisible: false,
    dialogPdfVisible: false,
    dialogImportVisible: false,
    showViewer: false,
    docxUrl: '',
    excelUrl: '',
    pdfUrl: '',
    fileName: '',
    previewList: [] as string[],
  });

  const showAdvanceQueryUI = ref(false);
  const printDialogRef = ref();
  const editDialogRef = ref();
  const loading = ref(false);
  const tableData = ref<any>([]);
  const queryParams = ref<any>({});
  const tableParams = ref({
    page: 1,
    pageSize: 10,
    total: 0,
  });
  const importData = ref<any>([]);
  const checkeds = ref<any>([])

  const printBanjiTitle = ref("");
  const editBanjiTitle = ref("");

  // 改变高级查询的控件显示状态
  const changeAdvanceQueryUI = () => {
    showAdvanceQueryUI.value = !showAdvanceQueryUI.value;
  }
  

  // 查询操作
  const handleQuery = async () => {
    loading.value = true;
    var res = await pageBanji(Object.assign(queryParams.value, tableParams.value));
    tableData.value = res.data.result?.items ?? [];
    tableParams.value.total = res.data.result?.total;
    loading.value = false;
  };

  // 打开新增页面
  const openAddBanji = () => {
    editBanjiTitle.value = '添加班级';
    editDialogRef.value.openDialog({});
  };

  // 打开打印页面
  const openPrintBanji = async (row: any) => {
    printBanjiTitle.value = '打印各班学生名单';
    var res = await getAPI(SysPrintApi).apiSysPrintPrintNameGet('各班学生名单');
	  var printTemplate = res.data.result as SysPrint;
    var template = JSON.parse(printTemplate.template);
    let printData = JSON.parse(JSON.stringify(checkeds.value));
    if(printData.length == 0){
      ElMessageBox.alert('请至少选择一个班级');
      return;
    }
    for(var i=0;i<printData.length;i++){
      printData[i]['printDate'] = formatDate(new Date(), 'YYYY-mm-dd HH:MM:SS');
      var studentRes = await pageStudent({banjiId:printData[i].id,pageSize:1000})
      printData[i]['table'] = studentRes.data.result?.items ?? [];
    }
    console.log(printData);
    printDialogRef.value.showDialog(new hiprint.PrintTemplate({template: template}), printData,'各班学生名单',template.panels[0].width);
  }
  
  // 打开编辑页面
  const openEditBanji = (row: any) => {
    editBanjiTitle.value = '编辑班级';
    editDialogRef.value.openDialog(row);
  };

  // 删除
  const delBanji = (row: any) => {
    ElMessageBox.confirm(`确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
  .then(async () => {
    await deleteBanji(row);
    handleQuery();
    ElMessage.success("删除成功");
  })
  .catch(() => {});
  };

  // 改变页面容量
  const handleSizeChange = (val: number) => {
    tableParams.value.pageSize = val;
    handleQuery();
  };

  // 改变页码序号
  const handleCurrentChange = (val: number) => {
    tableParams.value.page = val;
    handleQuery();
  };

  const teacherBzrIdDropdownList = ref<any>([]); 
  const getTeacherBzrIdDropdownList = async () => {
    let list = await getTeacherBzrIdDropdown();
    teacherBzrIdDropdownList.value = list.data.result ?? [];
  };

  // 打开上传页面
  const openUploadDialog = () => {
    state.fileList = [];
    state.dialogUploadVisible = true;
  };

  // 通过onChanne方法获得文件列表
  const handleChange = (file: any, fileList: []) => {
    state.fileList = fileList;
  };

  // 上传
  const uploadFile = async () => {
    if (state.fileList.length < 1) return;
    var res = await getAPI(SysFileApi).apiSysFileUploadFilePostForm(state.fileList[0].raw);
    handleQuery();
    ElMessage.success('上传成功');
    state.dialogUploadVisible = false;
    var r = await importPreviewBanji(res.data.result?.id);
    importData.value = r.data.result ?? [];
    state.dialogImportVisible = true;
  };
  const Import= async () => {
    var r = await importBanji(importData.value);
    if(r.status === 200){
      ElMessage.success('导入成功');  
    }else{
      ElMessage.error(r.message);
    }
    state.dialogImportVisible = false;
    handleQuery();
  };

  const download = () => {
    let fileUrl = '/download/banji.xlsx';////teacher.xlsx Upload
    downloadByUrl({ url: fileUrl });
  };

  
  const handleSelectionChange = (selection) => {
    //multipleSelection.value = val
    checkeds.value = selection.map((item) => item)
    console.log(checkeds.value);
  }

  getTeacherBzrIdDropdownList();
  
  handleQuery();
</script>
<style scoped>
:deep(.el-ipnut),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>

